local zhuihuan = fk.CreateSkill {

  name = "joy__zhuihuan",

  tags = {  },

}



zhuihuan:addEffect(fk.EventPhaseStart, {
  name = "joy__zhuihuan",
  anim_type = "defensive",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(zhuihuan.name) and player.phase == Player.Finish
  end,
  on_cost = function(self, event, target, player, data)
    local to = player.room:askForChoosePlayers(player, table.map(player.room.alive_players, Util.IdMapper), 1, 1, "#joy__zhuihuan-choose", zhuihuan.name, true, true)
    if #to > 0 then
      event:setCostData(self, to[1])
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    player.room:addPlayerMark(player.room:getPlayerById(event:getCostData(self)), zhuihuan.name, 1)
  end,
})

zhuihuan:addEffect(fk.EventPhaseStart, {
  name = "#joy__zhuihuan_delay",
  anim_type = "offensive",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player.phase == Player.Start and player:getMark("joy__zhuihuan") ~= 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "joy__zhuihuan", 0)
    local mark = player:getTableMark( "joy__zhuihuan_record")
    local targets = table.filter(room:getAlivePlayers(), function (p)
      return table.contains(mark, p.id)
    end)
    room:setPlayerMark(player, "joy__zhuihuan_record", 0)
    for _, p in ipairs(targets) do
      if player.dead then break end
      if not p.dead then
        if p.hp > player.hp then
          room:damage({
            from = player,
            to = p,
            damage = 2,
            damageType = fk.NormalDamage,
            skillName = "joy__zhuihuan"
          })
        else
          local cards = table.filter(p:getCardIds(Player.Hand), function (id)
            return not p:prohibitDiscard(Fk:getCardById(id))
          end)
          cards = table.random(cards, 2)
          if #cards > 0 then
            room:throwCard(cards, "joy__zhuihuan", p, p)
          end
        end
      end
    end
  end,
})
zhuihuan:addEffect(fk.Damaged, {
  refresh_events = {fk.Damaged},
  can_refresh = function(self, event, target, player, data)
    return player == target and player:getMark("joy__zhuihuan") ~= 0 and data.from
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local mark = player:getTableMark( "joy__zhuihuan_record")
    table.insert(mark, data.from.id)
    room:setPlayerMark(player, "joy__zhuihuan_record", mark)
  end,
})

return zhuihuan